package com.c.ctgproject.ui.collect

import android.content.Intent
import com.c.ctgproject.R
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityPowerBatteryInWarehourseSingleBinding
import com.c.ctgproject.entity.guang.BatteryInWarehouseEntity
import com.c.ctgproject.entity.guang.PowerBatteryDetailEntity
import com.c.ctgproject.enum.DictionaryMenuEnum
import com.c.ctgproject.event.PositionEvent
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.utils.*
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.widget.ninegridview.NineGridBean
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.startActivity
import java.io.File

/**
 *作者:LiBW
 *创建日期: 2021/9/16
 *描述:动力电池散件入库 页面 电池散件入库页面
 */
class PowerBatteryInWarehouseSingleActivity : BaseActivityV2() {
    private val mBinding by lazy { ActivityPowerBatteryInWarehourseSingleBinding.inflate(layoutInflater) }
    override fun getLayout() = mBinding.root

    //如果此处有值则表示 是从我的录入里面回来的数据重新编辑提交
    private val orderId by lazy { intent.getIntExtra(MyConstants.ORDER_ID, -1).handlerNull() }
    //图片处理
    private val imageShowList = ArrayList<String>()
    private val imageResultCode = 100
    //电池ID
//    private var pbId = -1
    override fun event() {
        mBinding.mPhotoNGV.init(this, imageShowList, 3, imageResultCode)
        if (orderId != "-1") {
            ApiMethods.apiSubscribe(ApiMethods.retrofit.batteryDetail(orderId), MyObserverHandlerLoading(this, loading) {
                MyLog.d("动力电池详情$it")
                val data = getGson().fromJson(it, PowerBatteryDetailEntity::class.java).data
                data?.let { bean ->
//                    bean.pbId?.let { id ->
//                        pbId = id
//                    }
                    batteryName = bean.batteryName.handlerNull()
                    mBinding.batteryName.text = batteryName
                    batteryFrom = bean.batterySource.handlerNull()
                    mBinding.batterySource.text = batteryFrom
                    mBinding.count.textSet(bean.count.handlerNull())
                    mBinding.driverName.textSet(bean.driverName.handlerNull())
                    mBinding.driverPlate.textSet(bean.driverPlate.handlerNull())
                    mBinding.tollET.textSet(bean.toll.handlerNull())
                    //入库单备注
                    mBinding.mRemarkET.textSet(bean.remark.handlerNull())
                    //旧图片
                    bean?.imgUrls?.let { images ->
                        val resultList: MutableList<NineGridBean> = ArrayList()
                        images.forEach { bean ->
                            val nineGirdData = NineGridBean(bean)
                            imageShowList.add(bean)
                            resultList.add(nineGirdData)
                        }
                        mBinding.mPhotoNGV.addDataList(resultList)
                    }
                    when (bean.batteryType) {
                        1 -> {
                            mBinding.mDCB.performClick()
                        }
                        2 -> {
                            mBinding.mMZ.performClick()
                        }
                        3 -> {
                            mBinding.mDX.performClick()
                        }
                    }

                }
            })
        }

    }

    private var batteryType = 1
    private var batteryName = ""
    private var batteryFrom = ""
    override fun click() {
        //我的录入
        mBinding.mMyInputTV.setOnClickListener {
            startActivity<BatteryMyInputActivity>()
        }
        //选择电池名称
        mBinding.mDictionarySelectLL.setOnClickListener {
            DictionaryMenuActivity.jumpToDictionary(this, DictionaryMenuEnum.BATTERY.menuCode, true, arrayListOf(batteryName))
        }
        //选择电池来源
        mBinding.mFromLL.setOnClickListener {
            DictionaryMenuActivity.jumpToDictionary(this, DictionaryMenuEnum.SUPPLIER.menuCode, true, arrayListOf(batteryFrom), true, 1001)
        }
        mBinding.mRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.mDCB -> {
                    batteryType = 1
                }
                R.id.mMZ -> {
                    batteryType = 2
                }
                R.id.mDX -> {
                    batteryType = 3
                }
            }
        }
        mBinding.mConfirmBTN.setOnClickListener {
            val count = mBinding.count.text.handlerNull()
            when {
                batteryName.isEmpty() -> showToast("请选择电池名称")
                count.isEmpty() -> showToast("请输入数量")
                batteryFrom.isEmpty() -> showToast("请选择电池来源")
                else -> {
                    if (imageShowList.isEmpty()){
                        showToast("请上传照片")
                    }

//            if (mBinding.batteryCount.text.handlerNull().isEmpty()) {
//                showToast("请输入电池数量")
//                mBinding.mCountLL.myShake()
//                return@setOnClickListener
//            }




                    //所有本地文件的图片
                    val filePathList = ArrayList<String>()
                    imageShowList.forEach {
                        if (!it.startsWith("http")) {
                            filePathList.add(it)
                        }
                    }

                    if (filePathList.isNotEmpty()) {
                        val fileList = ArrayList<File>()
                        var index = 0
                        filePathList.forEach {
                            index++
                            val file = File(it)
                            //图片压缩
//                            val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
//                    val newFile = ImageUtil.imageWaterMark(this, file, index)
                            val newFile: File = WaterRemark.handlerWaterRemark2File(this, file, index.toString())
                            fileList.add(newFile)
                        }
                        //将文件传给服务器后获取地址
                        upDataFile(fileList) {
                            val dataList = ArrayList<String>()
                            it?.forEach { b ->
                                dataList.add(b.fileUrl.handlerNull())
                            }
                            //旧的也给他
                            imageShowList.forEach { bean ->
                                if (bean.startsWith("http")) {
                                    dataList.add(bean)
                                }
                            }

                            submitToHttp(dataList)
                        }
                    } else {
                        //没有新文件 但是有旧的url
                        if (imageShowList.isNotEmpty()) {
                            submitToHttp(imageShowList)
                        } else {
                            submitToHttp(arrayListOf())
                        }
                    }
                }
            }
        }
    }
    private fun submitToHttp(imageList: ArrayList<String>) {
        if (imageList.isEmpty()){
            showToast("请上传电池照片")
            return
        }

        val map = HashMap<String, Any?>()
        val count = mBinding.count.text.handlerNull()
        val pictureList=ArrayList<Map<String,String>>()
        imageList.forEach {
            val pictureMap=HashMap<String,String>()
            pictureMap["picUrl"]=it
            pictureList.add(pictureMap)
        }
        map["imgUrlList"]= imageList
        map["batteryName"] = batteryName
        map["batterySource"] = batteryFrom
        map["count"] = count
        map["batteryType"] = batteryType
        map["driverName"] = mBinding.driverName.text.handlerNull()
        map["driverPlate"] = mBinding.driverPlate.text.handlerNull()
        map["remark"] = mBinding.mRemarkET.text.handlerNull()
        map["toll"] = mBinding.tollET.text.handlerNull()
        if (orderId != "-1") {
            //说明是编辑的单子
            map["orderId"]=orderId
//                            map["pbId"]=pbId
            ApiMethods.apiSubscribe(ApiMethods.retrofit.powerBatteryInWarehouseSingleUpdate(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                MyLog.d("回调:$it")
                showToast("提交成功")
                finish()
            })
        } else {
            ApiMethods.apiSubscribe(ApiMethods.retrofit.powerBatteryInWarehouseSingle(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                MyLog.d("回调:$it")
                showToast("提交成功")
                finish()
            })
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let { result ->
            //字典回调
            if (requestCode == 1000) {
                val name = result.getStringExtra(MyConstants.NAME)
                batteryName = name.handlerNull()
                mBinding.batteryName.text = name.handlerNull()
            }
            if (requestCode == 1001) {
                val name = result.getStringExtra(MyConstants.NAME)
                batteryFrom = name.handlerNull()
                mBinding.batterySource.text = name.handlerNull()
            }
            when (requestCode) {
                //图片回调
                imageResultCode -> {
                    val list: List<ImageBean>? = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
                    val resultList: MutableList<NineGridBean> = ArrayList()
                    list?.forEach { imageBean ->
                        val nineGirdData = NineGridBean(imageBean.imagePath)
                        imageShowList.add(imageBean.imagePath)
                        resultList.add(nineGirdData)
                    }
                    mBinding.mPhotoNGV.addDataList(resultList)
                }
                else -> {

                }
            }
        }
    }
}